package com.jpl.seminar.ui.util;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.ThemeResource;

public final class ExampleUtil {

	public static final Object iso3166_PROPERTY_NAME = "name";
	public static final Object iso3166_PROPERTY_SHORT = "short";
	public static final Object iso3166_PROPERTY_FLAG = "flag";

	public static Map<String, Locale> countries = new HashMap<String, Locale>();

	static {
		for (Locale locale : Locale.getAvailableLocales()) {
			if (locale.getCountry() != null && !"".equals(locale.getCountry())) {
				countries.put(locale.getCountry(), locale);
			}
		}
	}

	public static IndexedContainer getISO3166Container(Locale locale) {
		IndexedContainer c = new IndexedContainer();
		fillIso3166Container(c, locale);
		return c;
	}

	private static void fillIso3166Container(IndexedContainer container, Locale theLocale) {

		container.addContainerProperty(iso3166_PROPERTY_NAME, String.class, null);
		container.addContainerProperty(iso3166_PROPERTY_SHORT, String.class, null);
		container.addContainerProperty(iso3166_PROPERTY_FLAG, Resource.class, null);
		for (Entry<String, Locale> country : countries.entrySet()) {
			String id = country.getKey();
			String name = country.getValue().getDisplayCountry(theLocale);

			Item item = container.addItem(id);
			item.getItemProperty(iso3166_PROPERTY_NAME).setValue(name);
			item.getItemProperty(iso3166_PROPERTY_SHORT).setValue(id);
			item.getItemProperty(iso3166_PROPERTY_FLAG).setValue(new ThemeResource("./icons/flags/" + id.toLowerCase() + ".gif"));
		}
		container.sort(new Object[] { iso3166_PROPERTY_NAME }, new boolean[] { true });
	}
}